<?php

namespace App\Exports;


use App\Models\ArchiveManageVolume;
use App\Models\Humidity;
use App\Models\Project;
use App\Models\Storeroom;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Worksheet\PageMargins;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithTitle;

class HumidityExport implements FromCollection, WithColumnWidths, WithStyles, WithCustomStartCell, WithTitle
{
    use Exportable;

    protected $totalRows;
    protected $projectId;
    protected $type;
    protected $whichYear;
    protected $whichMonth;
    protected $yearMonth;
    protected $sheetName;
    protected $sheetTitle;
    protected $redisKey;

    public function __construct($projectId, $whichYear, $whichMonth, $yearMonth)
    {
        $projectName = Project::query()->where('id', $projectId)->value('title');

        $this->projectId  = $projectId;
        $this->whichYear  = $whichYear;
        $this->whichMonth = $whichMonth;
        $this->yearMonth  = $yearMonth;
        $this->sheetName  = '档案室温湿度登记表';
        $this->sheetTitle = $projectName . $this->sheetName . '档案室温湿度登记表';
        $this->redisKey   = get_rand_str('humidity');
    }

    public function collection()
    {
        $thisQuery = Humidity::query()->where('project_id', $this->projectId);
        if ($this->whichYear) {
            $whichYear = $this->whichYear;
            $whichYear = str_replace('年', '', $whichYear);
            $thisQuery->where('which_year', $whichYear);
        }
        if ($this->whichMonth) {
            $whichMonth = $this->whichMonth;
            if ($whichMonth != '全部') {
                $whichMonth = str_replace('月', '', $whichMonth);
                $thisQuery->where('which_month', $whichMonth);
            }
        }
        $list = $thisQuery->orderBy('serial_no')->get();
        if ($list->isEmpty()) return [];
        $list = $list->toArray();
        $r_list = [];
        foreach ($list as $key=>$val) {
            if ($val['time_slot'] == '上午') {
                redis()->lpush($this->redisKey, $key + 3);
            }
            $tmp                = [];
            $tmp['serial_no']   = $val['serial_no'];
            $tmp['which_year']  = $val['which_year'];
            $tmp['which_month'] = $val['which_month'];
            $tmp['which_day']   = $val['which_day'];
            $tmp['time_slot']   = $val['time_slot'];
            $tmp['temperature'] = $val['temperature'];
            $tmp['humidity']    = $val['humidity'];
            $tmp['remark']      = $val['remark'];
            $r_list[]           = $tmp;
        }
        $this->totalRows = count($r_list) + 2;

        return collect($r_list);
    }

    /**
     * 从哪个单元格开始渲染数据，数据集合如 $list
     * @return string
     */
    public function startCell(): string
    {
        return 'A3';
    }

    /**
     * 设置列宽
     * @return array
     */
    public function columnWidths(): array
    {
        return [
            'A' => 10, 'B' => 10, 'C' => 10, 'D' => 12, 'E' => 12, 'F' => 12, 'G' => 12, 'H' => 10
        ];
    }

    /**
     * 样式设置
     * @param Worksheet $sheet
     * @throws PhpSpreadsheetException
     */
    public function styles(Worksheet $sheet)
    {
        /**
         * 设置页边距
         */
        $pageMargins = new PageMargins();
        $pageMargins->setTop(0.5);
        $pageMargins->setRight(0.6);
        $pageMargins->setLeft(0.8);
        $sheet->setPageMargins($pageMargins);

        $sheet->getDefaultRowDimension()->setRowHeight(32); //设置行高(全部行高)
        $sheet->getStyle('A1:H' . $this->totalRows)->getFont()->setName('宋体'); //宋体
        $sheet->getStyle('A1:H' . $this->totalRows)->getFont()->setSize(12); //大小
        $sheet->getStyle('A1:H' . $this->totalRows)->getAlignment()->setWrapText(true); //自动换行
        $sheet->mergeCells('A1:H1');
        $sheet->setCellValue('A1', $this->sheetTitle);

        /**
         * 属性名设置
         */
        $sheet->setCellValue('A2', '序号');
        $sheet->setCellValue('B2', '年度');
        $sheet->setCellValue('C2', '月份');
        $sheet->setCellValue('D2', '日期');
        $sheet->setCellValue('E2', '时间段');
        $sheet->setCellValue('F2', '温度');
        $sheet->setCellValue('G2', '湿度');
        $sheet->setCellValue('H2', '备注');

        /**
         * 顶部案卷目录样式设置
         */
        $sheet->getStyle('A1:H' . $this->totalRows)->getAlignment()->setVertical('center');//垂直居中
        $sheet->getStyle('A1:H' . $this->totalRows)->getAlignment()->setHorizontal('center');//水平居左
        $morningCount = redis()->llen($this->redisKey);
        for ($i = 0; $i < $morningCount; $i++) {
            $morningRow   = redis()->rpop($this->redisKey);
            $afternoonRow = $morningRow + 1;
            $sheet->mergeCells("D{$morningRow}:D{$afternoonRow}");
        }

        /**
         * 设置边框
         */
        $styleArray = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN //细边框
                ]
            ]
        ];
        $sheet->getStyle('A1:H' . $this->totalRows)->applyFromArray($styleArray);
    }

    /**
     * sheet名称
     * @return string
     */
    public function title(): string
    {
        return $this->yearMonth;
    }


}
